﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using MxitAPI;

namespace MxitGUI {
    public partial class LoginWindow : Form {

        private static int threadNumber = 0;

        public LoginWindow() {
            InitializeComponent();
            SetupMxitApplication();

            Connection.Instance.LoginEvent += new ConnectionEventHandler( this.LoginEvent );
        }

        public void SetupMxitApplication() {
            Connection connection = Connection.Instance;
            TcpServerInfo serverInfo = new TcpServerInfo();
            serverInfo.Address = "41.191.124.48";
            serverInfo.Port = 9119;
            serverInfo.Timeout = 20000;
            connection.PrimaryServer = serverInfo;
            connection.MessageTranceiver = new TcpMessageTransceiver();

            SendQueueWorker sendQueueWorker = new SendQueueWorker( ProtocolMessageSendQueue.Instance, connection.MessageTranceiver );
            Thread t = new Thread( new ThreadStart( sendQueueWorker.SendProtocolMessages ) );

            t.Name = "SendQueueWorkerThread" + threadNumber++;
            t.Start();
        }

        private void LoginBtn_Click( object sender, EventArgs e ) {
            Button loginButton = sender as Button;
            loginButton.Text = "Logging In";
            loginButton.Enabled = false;

            // Check to see if this user has registered with this mxit client
            ApplicationInfo app = ApplicationInfo.Instance;
            app.ProductId = string.Empty;
            app.LoadUserSettings( txtPhoneNumber.Text );

            // If the user has not retreived his product id, do it now
            if ( app.ProductId == string.Empty ) {
                bool clientRegistered = false;
                do {
                    RegisterClientWindow registerClientWindow = new RegisterClientWindow( txtPhoneNumber.Text );
                    DialogResult result = registerClientWindow.ShowDialog();
                    // If the user cancelled the client registration process, cancel the login process
                    if ( result == DialogResult.Cancel ) {
                        BtnLoginEnable();
                        return;
                    }
                    // If the client registration process completed successfully, set a variable to stop the loop
                    else if (registerClientWindow.Success ) {
                        clientRegistered = true;
                    }
                    else {
                        // If their was an error in the client registration process show an error
                        if ( MessageBox.Show( "There was an error with the client registration process, please try again" ) == DialogResult.Cancel ) {
                            BtnLoginEnable();
                            return;
                        }
                    }
                    
                    registerClientWindow.Dispose();
                } while ( !clientRegistered );

                app.SaveUserSettings();
            }

            // Login
            LoginHandler login = new LoginHandler( txtPhoneNumber.Text, txtPassword.Text );
            login.Execute();
        }

        private void BtnLoginEnable() {
            lblStatus.Text = "Login Failed, please try again";
            btnLogin.Text = "Login";
            btnLogin.Enabled = true;
        }

        private void LoginEvent( Connection connection, EventArgs e ) {

            /*  if ( InvokeRequired ) {
                  Invoke( new Action<object, EventArgs>( LoginEvent ), connection, e );
                  return;
              }*/

            if ( this.InvokeRequired ) {
                this.Invoke( new ConnectionEventHandler( LoginEvent ), connection, e );
                return;
            }


            if ( connection.ConnectionStatus == ConnectionStatus.Disconnected ) {
                BtnLoginEnable();
            }
            else {
                lblStatus.Text = "Login Successful";
                btnLogin.Text = "Loading";
                MainWindow mainWindow = new MainWindow( this );
                mainWindow.Show();
                this.Hide();
            }
        }


        public void Exit() {
            Application.Exit();
        }

    }
}
